from rest_framework.response import Response
from rest_framework.views import APIView
from users.models import User
from datetime import date, timedelta
from rest_framework.permissions import IsAdminUser
from goods.models import GoodsVisitCount

# 用户总量统计
class UserCountView(APIView):
    """
        用户总量统计
    """
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self,request):
        # 查询用户总数
        count = User.objects.filter(is_staff=False).count()
        # 返回结果
        return Response({'count':count})

# 日增用户统计
class UserDayCountView(APIView):
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当天时间
        now_date = date.today()
        # 查询日增用户总量    __gte 大于等于   __lte 小于等于
        count = User.objects.filter(is_staff=False,date_joined__gte=now_date).count()
        # 返回结果
        return Response({'count': count})

# 日活用户统计
class UserDayAciveCountView(APIView):
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当天时间
        now_date = date.today()
        # 查询日活用户
        count = User.objects.filter(is_staff=False,last_login__gte=now_date).count()
        # 返回结果
        return Response({'count':count})

# 当天下单用户数量统计
class UserDayOrderCountView(APIView):
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当天时间
        now_date = date.today()
        # 查询当天下单用户总数
        users = User.objects.filter(is_staff=False,orders__create_time__gte=now_date)
        # 去重 强转set
        user = set(users)
        count = len(user)
        # 返回结果
        return Response({'count':count})

# 一个月范围内的每天注册用户总量统计
class UserMonthCountView(APIView):
    # 权限指定
    permission_classes = [IsAdminUser]
    def get(self,request):
        # 获取当天时间
        now_date = date.today()
        # 获取30天之前的日期
        old_date = now_date - timedelta(30)
         # 遍历,从30之前开始遍历查询每天的用户注册量
        date_list = []
        for i in range(30):
             # 起始日期
             index_date =old_date + timedelta(i)
             # 起始日期的下一天日期
             next_date = old_date + timedelta(i + 1)
             count = User.objects.filter(is_staff=False,date_joined__gte=index_date,date_joined__lt=next_date).count()
             date_list.append({'count':count,'date':index_date})

         # 返回结果
        return Response(date_list)

# 商品分类访问量统计
class GoodsCountView(APIView):
    # 权限指定
    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当天时间
        now_date = date.today()
        # 获取商品分类访问量
        goods = GoodsVisitCount.objects.filter(date__gte=now_date)
        data_list = []
        for good in goods:
            count = good.count
            # 获取商品分类的名字
            category = good.category.name
            data_list.append({"count": count, 'category': category})
        # 返回结果
        return Response(data_list)










